package com.tomorrowbbs.controller;

import com.tomorrowbbs.annotation.GlobalInterceptor;
import com.tomorrowbbs.controller.base.ABaseController;
import com.tomorrowbbs.domain.config.WebConfig;
import com.tomorrowbbs.domain.constants.Constants;
import com.tomorrowbbs.domain.enums.ResponseCodeEnum;
import com.tomorrowbbs.domain.vo.ResponseVo;
import com.tomorrowbbs.exception.BusinessException;
import com.tomorrowbbs.utils.StringTools;
import org.apache.commons.lang3.ArrayUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;


@RestController
@RequestMapping("/file")
public class FileController extends ABaseController {
    private static final Logger logger = LoggerFactory.getLogger(FileController.class);

    @Autowired
    private WebConfig webConfig;

    @RequestMapping("/uploadImage")
    @GlobalInterceptor(checkLogin = true)
    public ResponseVo uploadImage( MultipartFile file) {

        if (file == null){
            throw new BusinessException(ResponseCodeEnum.CODE_600);
        }

        String fileName = file.getOriginalFilename();
        String fileExtName = StringTools.getFileSuffix(fileName);
        // 校验文件后缀
        if(!ArrayUtils.contains(Constants.IMAGE_SUFFIX, fileExtName)){
            throw new BusinessException(ResponseCodeEnum.CODE_600);
        }

        String path = copyFile(file);
        Map<String,String> fileMap = new HashMap<>();
        fileMap.put("fileName",path);
        return getSuccessResponseVo(fileMap);
    }

    private String copyFile(MultipartFile file) {
        try {
            String fileName = file.getOriginalFilename();
            String fileExtName = StringTools.getFileSuffix(fileName);
            String fileRealName = StringTools.getRandomString(Constants.LENGTH_30) + fileExtName;
            String folderPath = webConfig.getProjectFolder() + Constants.FILE_FOLDER_FILE + Constants.FILE_FOLDER_TEMP;
            File folder = new File(folderPath);
            if(!folder.exists()){
                folder.mkdirs();
            }
            File uploadFile = new File(folderPath+"/"+fileRealName);
            file.transferTo(uploadFile);
            return Constants.FILE_FOLDER_TEMP_2 +"/"+  fileRealName;
        }catch (Exception e){
            throw new BusinessException("上传文件失败");
        }
    }

    @RequestMapping("getImage/{imageFolder}/{imageName}")
    public void getImage(HttpServletResponse response, @PathVariable String imageFolder, @PathVariable String imageName){
        readImage(response,imageFolder,imageName);
    }

    @RequestMapping("getAvatar/{userId}")
    public void getAvatar(HttpServletResponse response, @PathVariable String userId){
        String avatarFolderName = Constants.FILE_FOLDER_FILE + Constants.FILE_FOLDER_AVATAR_NAME;
        String avatarPath = webConfig.getProjectFolder() + avatarFolderName + userId + Constants.AVATAR_SUFFIX;
        File avararFolder = new File(avatarFolderName);
        if (!avararFolder.exists()){
            avararFolder.mkdirs();
        }
        File file = new File(avatarPath);
        String imageName = userId + Constants.AVATAR_SUFFIX;
        if (!file.exists()){
            imageName = Constants.AVATAR_DEFAULT;
        }

        readImage(response,Constants.FILE_FOLDER_AVATAR_NAME,imageName);
    }

    private void readImage(HttpServletResponse response, String imageFolder, String imageName){
        ServletOutputStream sos = null;
        FileInputStream in = null;
        ByteArrayOutputStream bos = null;

        try {
            if(StringTools.isEmpty(imageFolder) || StringUtils.isBlank(imageName)){
                return;
            }
            String imageSuffix = StringTools.getFileSuffix(imageName);
            String filePath = webConfig.getProjectFolder() + Constants.FILE_FOLDER_FILE+ Constants.FILE_FOLDER_IMAGE + imageFolder + "/" + imageName;
            if(Constants.FILE_FOLDER_TEMP_2.equals(imageFolder) || imageFolder.contains(Constants.FILE_FOLDER_AVATAR_NAME)){
                filePath = webConfig.getProjectFolder() + Constants.FILE_FOLDER_FILE + imageFolder+ "/" + imageName;
            }
            File file = new File(filePath);
            if(!file.exists()){
                return;
            }
            imageSuffix = imageSuffix.replace(".","");
            if(!Constants.FILE_FOLDER_AVATAR_NAME.equals(imageFolder)){
                response.setHeader("Cache-Control","max-age=2592000");
            }
            response.setContentType("image/"+imageSuffix);
            in = new FileInputStream(file);
            sos = response.getOutputStream();
            bos = new ByteArrayOutputStream();
            int ch = 0;
            while (-1!=(ch=in.read())){
                bos.write(ch);
            }
            sos.write(bos.toByteArray());
        }catch (Exception e) {
            logger.error("读取图片异常",e);
        }finally {
            if (bos != null){
                try {
                    bos.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (sos != null){
                try{
                    sos.close();
                }catch (IOException e){
                    logger.error("IO异常",e);
                }
            }
        }
    }



}















